package com.dk.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dk.pojo.Game;
import com.dk.pojo.Position;
import com.dk.pojo.playerData.PlayerData;
import com.dk.pojo.playerData.PlayerDataVO;
import com.dk.service.GamesService;
import com.dk.service.PlayerDataService;
import com.dk.service.PosService;
import com.dk.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 玩家详情管理
 */
@Controller
@RequestMapping("player")
public class PlayerController {
    @Autowired
    private PlayerDataService playerDataService;
    @Autowired
    private PosService posService;
    @Autowired
    private GamesService gamesService;

    @RequestMapping("toShow")
    public String toShow(){
        return "/player/show";
    }

    @RequestMapping("toPlayerShow")
    public String toPlayerShow(){
        return "/player/playerShow";
    }

    //系统创建者看到的
    @RequestMapping("getInfo")
    @ResponseBody
    public Map<String,Object> getInfoServer(PlayerData playerData,
                                            Integer pageNumber,
                                            Integer pageSize){
        PageInfo<PlayerData> page =  playerDataService.show(playerData,pageNumber,pageSize);
        //需要total:总条数 rows:结果集 (都是key,value结合,所以用map)
        Map<String,Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("rows",page.getList());
        return map;

    }

    //获取当前登录玩家的个人信息
    @RequestMapping("getPlayerInfo")
    @ResponseBody
    public Map<String,Object> getPlayerInfo(HttpServletRequest request,
                                            @RequestParam(defaultValue = "1")Integer pageNumber,
                                            @RequestParam(defaultValue = "3")Integer pageSize){
        PlayerData player = (PlayerData) request.getSession().getAttribute("player");
        PageInfo<PlayerDataVO> page =  playerDataService.getPlayerInfo(player.getPlayerAccount(),pageNumber,pageSize);
        //需要total:总条数 rows:结果集 (都是key,value结合,所以用map)
        Map<String,Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("rows",page.getList());
        return map;

    }

    @RequestMapping("addInfo")
    @ResponseBody
    public boolean addInfo(PlayerData playerData){
        return playerDataService.addInfo(playerData);
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model){
        List<Position> position = posService.getInfo();
        model.addAttribute("position",position);
        List<Game> games = gamesService.getInfo();
        model.addAttribute("games",games);
        return "/player/add";
    }

    @RequestMapping("toUpdate/{id}")
    public String toUpdate(@PathVariable("id")Integer id, Model model){
        PlayerData playerData = playerDataService.toUpdatet(id);
        model.addAttribute("playerData",playerData);
        List<Position> position = posService.getInfo();
        model.addAttribute("position",position);
        List<Game> games = gamesService.getInfo();
        model.addAttribute("games",games);
        return "/player/update";
    }

    //个人面板修改
    @RequestMapping("toUpdateByPlayerAccount/{playerAccount}")
    public String toUpdateByPlayerAccount(@PathVariable("playerAccount")Integer playerAccount, Model model){
        PlayerData player = playerDataService.toUpdateByPlayerAccount(playerAccount);
        model.addAttribute("player",player);
        return "/player/playerUpdate";
    }

    @RequestMapping("updateInfo")
    @ResponseBody
    public boolean updateInfo(PlayerData playerData){
        return playerDataService.updateInfo(playerData);
    }

    @RequestMapping("deleteInfo/{id}")
    @ResponseBody
    public boolean deleteInfo(@PathVariable("id")Integer id){
        return playerDataService.deleteInfo(id);
    }

    /**
     * 登录
     */
    @RequestMapping("getInfod")
    @ResponseBody
    public Integer getInfo(PlayerData playerData, HttpServletRequest request, String vcode){
        //验证码
        String code = (String)request.getSession().getAttribute("code");
        if (!vcode.equalsIgnoreCase(code)) return 5;
        return playerDataService.getInfo(playerData,request);
    }

    /**
     * 登录验证账号是否存在
     */
    @RequestMapping("selectUser")
    @ResponseBody
    public Integer selectUser(PlayerData playerData){
        return playerDataService.selectUser(playerData);
    }

    @RequestMapping("logUp")
    public String logUp(HttpServletRequest request){
        request.getSession().removeAttribute("player");
        return "redirect:/";
    }

    /**
     * 阿里云上传图片
     */
    @RequestMapping("upload")
    @ResponseBody
    public Result insertInfo(@RequestParam("image") MultipartFile image){
        //传统写法：
        // 1. 获取一个路径用来存放图片位置
        // 2. 调用MultipartFile输出功能将图片以io流的方式输出到文件夹里
        // 3. 并且返回图片名称即可（详情可见news项目中的上传方法）

        //现在：
        //改用第三方调用方式上传图片，将图片放到阿里云上，而不是放到我们指定的文件夹里（因为我们调用文件夹io流性能非常差
        /*
            调用第三方接口：有两种方式
            第一种是 SDK 方式（导jar包调用方法）
            第二种是：API 方式（不需要导jar包，看接口文档，使用http方式调用（都需要掌握）
            这里是讲的第一种方法
         */

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String https = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tNsWhDy41FeVhm8fudw";
        String accessKeySecret = "GGhLSQqcpheEfF0pk4t9GiP0833TtZ";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(https + endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = null;
        //图片名
        String imagePath = "image/" + image.getOriginalFilename();
        //Bucket名称
        String bucket = "2107lcc";
        try {
            putObjectRequest = new PutObjectRequest(bucket,imagePath, image.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        };

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        //https://2107lcc.oss-cn-beijing.aliyuncs.com/image/0bd2697e-2ef1-472d-973d-0fe3be7d3051.JPG
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(https).append(bucket).append(".").append(endpoint).append("/").append(imagePath);
        return Result.ok().setData(stringBuilder.toString());
    }

}
